package com.cjkj.applet.service.impl;

import com.cjkj.applet.domain.AppletAccount;
import com.cjkj.applet.domain.THospitalUserSign;
import com.cjkj.applet.mapper.AppletAccountMapper;
import com.cjkj.applet.mapper.THospitalUserMapper;
import com.cjkj.applet.mapper.THospitalUserSignMapper;
import com.cjkj.applet.service.AppletAccountService;
import com.cjkj.common.core.exception.ServiceException;
import com.cjkj.common.security.utils.SecurityUtils;
import com.cjkj.system.api.domain.THospitalUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 *
 */
@Service
public class AppletAccountServiceImpl implements AppletAccountService{

    @Resource
    private AppletAccountMapper accountMapper;

    @Resource
    private THospitalUserMapper hospitalUserMapper;

    @Resource
    private THospitalUserSignMapper hospitalUserSignMapper;

    @Override
    public Boolean addAccount(AppletAccount account) {
        int insertFlag = accountMapper.insertAppletAccount(account);
        return insertFlag > 0;
    }

    @Override
    public AppletAccount getAccountByOpenId(String openId) {
        return accountMapper.selectAppletAccountByOpenId(openId);
    }

    @Override
    public int unbindDoctor() {
        return accountMapper.setDoctorNull(SecurityUtils.getAppUserId());
    }

    @Override
    public int bindDoctor(String doctorAccount, String doctorPassword) {

        // 判断医生账号是否存在
        THospitalUser hospitalUser = hospitalUserMapper.selectTHospitalUserByUserName(doctorAccount);
        if(hospitalUser == null) {
            throw new ServiceException("医生账号不存在！");
        }
        // 验证密码
        if(! SecurityUtils.matchesPassword(doctorPassword, hospitalUser.getPassword())) {
            throw new ServiceException("医生密码输入错误！");
        }

        // 当前账号ID
        Long appUserId = SecurityUtils.getAppUserId();
        AppletAccount account = new AppletAccount();
        account.setAccountId(appUserId);
        account.setDoctor(doctorAccount);
        return accountMapper.updateAppletAccount(account);
    }

    @Override
    public String getDoctorSign(String doctorAccount) {
        THospitalUser hospitalUser = hospitalUserMapper.selectTHospitalUserByUserName(doctorAccount);
        if(hospitalUser == null) {
            throw new ServiceException("医生账号不存在！");
        }

        THospitalUserSign tHospitalUserSign = hospitalUserSignMapper.selectOneByUserId(hospitalUser.getUserId());
        return tHospitalUserSign != null ? tHospitalUserSign.getSignImg() : "";
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void clearUserDoctorInfo(String doctorAccount) {
        accountMapper.setDoctorAccountEmpty(doctorAccount);
    }
}
